package com.rupeng.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rupeng.pojo.Subject;
import com.rupeng.service.SubjectService;
import com.rupeng.util.AjaxResult;
import com.rupeng.util.CommonUtils;

@Controller
@RequestMapping("/subject")
public class SubjectController {
	@Autowired
	private SubjectService subjectService;
	@RequestMapping("/list.do")
	public ModelAndView list() {
		List<Subject> subjects = subjectService.selectList();
		ModelAndView modelAndView = new ModelAndView("subject/list");
		modelAndView.addObject("subjects", subjects);
		return modelAndView;
	}
	@RequestMapping("/add.do")
	public ModelAndView addPage(Subject subject) {
		return new ModelAndView("subject/add");
	}
	@RequestMapping(value="/add.do",method=RequestMethod.POST)
	public @ResponseBody AjaxResult addSubmit(String name) {
		Subject subject = new Subject();
		subject.setName(name);
		if (CommonUtils.isEmpty(name)) {
			return AjaxResult.errorInstance("学科名称不能为空");
		}
		if (subjectService.isExisted(subject)) {
			return AjaxResult.errorInstance("学科名称已存在");
		}
		subjectService.insert(subject);
		return AjaxResult.successInstance("添加成功");
	}
	@RequestMapping(value="/update.do",method=RequestMethod.GET)
	public ModelAndView updatePage(Long id) {
		Subject subject = subjectService.selectOne(id);
		return new ModelAndView("subject/update","subject",subject);
	}
	@RequestMapping(value="/update.do",method=RequestMethod.POST)
	public @ResponseBody AjaxResult updateSubmit(Long id, String name) {
		if (CommonUtils.isEmpty(name)) {
			return AjaxResult.errorInstance("学科名不能为空");
		}
		Subject subject = new Subject();
		subject.setName(name);
		subject = subjectService.selectOne(subject);
		if (subject!=null && subject.getId()!=id) {
			return AjaxResult.errorInstance("学科名称已存在");
		}
		subject = new Subject();
		subject.setName(name);
		subject.setId(id);
		subjectService.update(subject);
		return AjaxResult.successInstance("修改学科名称成功");
	}
	@RequestMapping("/delete.do")
	public @ResponseBody AjaxResult delete(Long id) {
		subjectService.delete(id);
		return AjaxResult.successInstance("学科删除成功");
	}
}
